import React, { Component, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import { Form, Card, Tag, Table, Radio, Button, Input } from 'antd';

import TagSelect from 'components/TagSelect';
import StandardFormRow from 'components/StandardFormRow';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const DEFAULT_PAGE_SIZE = 20;
const DEFAULT_PAGE_INDEX = 1;

@connect(({ article, loading }) => ({
  article,
  loading: loading.models.article,
}))
@Form.create()
export default class Article extends Component {

  state = {
    articlePageNum: DEFAULT_PAGE_INDEX,
    articlePageSize: DEFAULT_PAGE_SIZE,
    articleKeywords: '',
    category: '',
    sorted: '',
  };

  componentDidMount() {
    this.initCategory();
    this.listArticle();
    this.fetchTotal();
  }

  listArticle = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'article/listArticle',
      payload: {
        ...this.state,
      },
    });
  };

  fetchTotal = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'article/total',
    })
  };

  initCategory = () => {
    const { dispatch }  = this.props;
    dispatch({
      type: 'article/listCategory',
    });
  };

  tagChange = (tag, checked) => {
    const { category } = this.state;
    const nextSelectedTags = checked
      ? [...category, tag]
      : category.filter(t => t !== tag);
    this.setState({ category: nextSelectedTags });
  };

  search = e => {
    e.preventDefault();
    const { category } = this.state;
    const { form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      this.setState({
        articlePageNum: DEFAULT_PAGE_INDEX,
        articlePageSize: DEFAULT_PAGE_SIZE,
        articleKeywords: fieldsValue.keywords,
        sorted: fieldsValue.sorted,
        category,
        },
        () => {
          this.listArticle();
        }
      );
    });
  };

  render() {
    const {
      form,
      article: { articleList, categoryList, articleTotal, total },
      loading,
    } = this.props;
    const { getFieldDecorator } = form;
    const { category, articlePageSize, articlePageNum } = this.state;

    const pager = {
      total: articleTotal,
      pageSize: articlePageSize,
      current: articlePageNum,
      onChange: (current, pageSize) => {
        this.setState({
            articlePageNum: current,
            articlePageSize: pageSize,
          },
          () => {
            this.listArticle();
          }
        );
      },
    };

    const columns = [
      {
        dataIndex: 'title',
        title: '题目',
        render: (val, record) => <a href={record.src} target="_bank">{val}</a>,
      },
      {
        dataIndex: 'category',
        title: '领域',
        width: 100,
        render: val => (
          <Tag color="blue" key={val}>
            {val}
          </Tag>
        ),
      },
      {
        dataIndex: 'view',
        title: '阅读',
        width: 100,
        render: val => {
          if(val >= 10000){
            return `${(parseFloat(val) / 10000).toFixed(2)}万`;
          }
          return val;
        },
      },
      {
        dataIndex: 'comment',
        title: '评论',
        width: 100,
        render: val => {
          if(val >= 10000){
            return `${(parseFloat(val) / 10000).toFixed(2)}万`;
          }
          return val;
        },
      },
      {
        dataIndex: 'add_time',
        title: '入库时间',
        width: 180,
        render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,

      },
      {
        dataIndex: 'update_time',
        title: '更新时间',
        width: 180,
        render: val =>
          val ? <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span> : <span>暂无更新</span>,
      },
      {
        dataIndex: 'publish_time',
        title: '发布时间',
        width: 180,
      },
      {
        dataIndex: 'name',
        title: '所属百家号',
        render: (val, record) => <a href={record.home_url} target="_bank">{val}</a>,
      },
    ];
    const content = (
      <div>
        当前已抓取文章 <span style={{ color:'red', fontSize: 20}}>{ total }</span> 篇, 爬虫状态: <span style={{ color: 'green', fontSize: 18}}> 运行中...</span>
      </div>
    );

    return (
      <PageHeaderLayout title="百家文章" content={content}>
        <Fragment>
          <Card bordered={false}>
            <Form layout="inline" onSubmit={this.search}>
              <StandardFormRow title="感兴趣 " block style={{ paddingBottom: 11 }}>
                <FormItem>
                  {getFieldDecorator('category')(
                    <TagSelect expandable>
                      {(categoryList || []).map(item => (
                        <Tag.CheckableTag key={item.id} checked={category.indexOf(item.name) > -1} onChange={checked => this.tagChange(item.name, checked)}> {item.name} </Tag.CheckableTag>
                      ))}
                    </TagSelect>
                  )}
                </FormItem>
              </StandardFormRow>
              <StandardFormRow title="排序" block style={{ paddingBottom: 11 }}>
                <FormItem>
                  {getFieldDecorator('sorted')(
                    <RadioGroup name="sorted">
                      <Radio value="">最新</Radio>
                      <Radio value="view">阅读</Radio>
                      <Radio value="comment">评论</Radio>
                    </RadioGroup>
                  )}
                </FormItem>
              </StandardFormRow>
              <StandardFormRow title="关键字" block style={{ paddingBottom: 11 }}>
                <FormItem>
                  {getFieldDecorator('keywords')(
                    <Input />
                  )}
                </FormItem>
              </StandardFormRow>
              <Button type="primary" htmlType="submit" icon="search">
                查询
              </Button>
            </Form>
          </Card>
          <Card style={{ marginTop: 24 }} bordered={false} bodyStyle={{ padding: '8px 32px 32px 32px' }}>
            <Table bordered={false} dataSource={articleList} rowKey="id" loading={loading} columns={columns} pagination={pager} />
          </Card>
        </Fragment>
      </PageHeaderLayout>
    );
  }
}
